<template>
  <div class="user-detail-container">
    <div class="header">
      <el-page-header @back="goBack" content="用户详情">
      </el-page-header>
      <div class="actions">
        <el-button type="primary" @click="showEditDialog" icon="el-icon-edit">编辑</el-button>
        <el-button type="danger" @click="handleDelete" icon="el-icon-delete">删除</el-button>
      </div>
    </div>
    
    <el-card class="user-info-card" shadow="hover">
      <div class="user-header">
        <el-avatar :size="80" class="user-avatar">
          <i class="el-icon-user"></i>
        </el-avatar>
        <div class="user-basic-info">
          <h2>{{ user.fullName || user.username }}</h2>
          <p class="username">@{{ user.username }}</p>
          <el-tag :type="userStatusType" class="status-tag">{{ userStatusText }}</el-tag>
        </div>
      </div>
      
      <div class="user-details">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>邮箱:</label>
              <span>{{ user.email }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>注册时间:</label>
              <span>{{ formatDateTime(user.createdAt) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>最后登录:</label>
              <span>{{ user.lastLogin ? formatDateTime(user.lastLogin) : '从未登录' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>用户ID:</label>
              <span>{{ user.id }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>角色:</label>
              <el-tag :type="user.role === 'ADMIN' ? 'danger' : 'info'">
                {{ user.role === 'ADMIN' ? '管理员' : '普通用户' }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    
    <el-card class="user-activity-card" shadow="hover">
      <div slot="header" class="card-header">
        <span>最近活动</span>
      </div>
      <div class="activity-list">
        <div class="activity-item" v-for="activity in recentActivities" :key="activity.id">
          <div class="activity-icon" :style="{ backgroundColor: getActivityColor(activity.type) }">
            <i :class="getActivityIcon(activity.type)"></i>
          </div>
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-description">{{ activity.description }}</div>
            <div class="activity-time">{{ activity.time }}</div>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="dialogVisible"
      width="500px"
      @close="handleDialogClose"
      class="edit-dialog"
    >
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userForm"
        label-width="80px"
        class="user-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="userForm.fullName" placeholder="请输入姓名"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import moment from 'moment'

export default {
  name: 'UserDetail',
  data() {
    return {
      dialogVisible: false,
      userForm: {
        id: null,
        username: '',
        email: '',
        fullName: ''
      },
      userFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        fullName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      recentActivities: [
        {
          id: 1,
          type: 'login',
          title: '用户登录',
          description: '用户成功登录系统',
          time: '2小时前'
        },
        {
          id: 2,
          type: 'update',
          title: '信息更新',
          description: '用户更新了个人信息',
          time: '1天前'
        },
        {
          id: 3,
          type: 'create',
          title: '创建任务',
          description: '用户创建了新的迁移任务',
          time: '3天前'
        }
      ]
    }
  },
  computed: {
    ...mapState('users', ['users']),
    user() {
      const userId = this.$route.params.id
      return this.users.find(u => u.id === parseInt(userId)) || {}
    },
    userStatusText() {
      if (this.user.lastLogin) {
        const lastLogin = new Date(this.user.lastLogin)
        const now = new Date()
        const diffHours = (now - lastLogin) / (1000 * 60 * 60)
        return diffHours < 24 ? '在线' : '离线'
      }
      return '未激活'
    },
    userStatusType() {
      if (this.user.lastLogin) {
        const lastLogin = new Date(this.user.lastLogin)
        const now = new Date()
        const diffHours = (now - lastLogin) / (1000 * 60 * 60)
        return diffHours < 24 ? 'success' : 'info'
      }
      return 'warning'
    }
  },
  methods: {
    ...mapActions('users', ['updateUser', 'deleteUser']),
    goBack() {
      this.$router.go(-1)
    },
    formatDateTime(datetime) {
      return datetime ? moment(datetime).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    getActivityIcon(type) {
      const iconMap = {
        'login': 'el-icon-user',
        'update': 'el-icon-edit',
        'create': 'el-icon-plus',
        'delete': 'el-icon-delete'
      }
      return iconMap[type] || 'el-icon-info'
    },
    getActivityColor(type) {
      const colorMap = {
        'login': '#409EFF',
        'update': '#E6A23C',
        'create': '#67C23A',
        'delete': '#F56C6C'
      }
      return colorMap[type] + '20' || '#409EFF20'
    },
    showEditDialog() {
      this.userForm = {
        id: this.user.id,
        username: this.user.username,
        email: this.user.email,
        fullName: this.user.fullName
      }
      this.dialogVisible = true
    },
    handleDialogClose() {
      this.$refs.userForm.resetFields()
    },
    async handleSave() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            await this.updateUser({
              id: this.userForm.id,
              userData: {
                email: this.userForm.email,
                fullName: this.userForm.fullName
              }
            })
            this.$message.success('用户信息更新成功')
            this.dialogVisible = false
          } catch (error) {
            this.$message.error(error.message || '操作失败')
          }
        }
      })
    },
    async handleDelete() {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.deleteUser(this.user.id)
          this.$message.success('删除成功')
          this.$router.push('/users')
        } catch (error) {
          this.$message.error(error.message || '删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.user-detail-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.actions {
  display: flex;
  gap: 10px;
}

.user-info-card {
  margin-bottom: 30px;
  border-radius: 10px;
  overflow: hidden;
}

.user-header {
  display: flex;
  align-items: center;
  padding: 30px;
  border-bottom: 1px solid #f0f0f0;
}

.user-avatar {
  background-color: #409EFF;
  margin-right: 30px;
}

.user-basic-info h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.username {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #909399;
}

.status-tag {
  font-size: 14px;
}

.user-details {
  padding: 30px;
}

.detail-item {
  display: flex;
  margin-bottom: 20px;
}

.detail-item label {
  width: 100px;
  font-weight: 500;
  color: #606266;
}

.detail-item span {
  flex: 1;
  color: #303133;
}

.user-activity-card {
  border-radius: 10px;
  overflow: hidden;
}

.card-header {
  font-weight: 600;
  font-size: 16px;
}

.activity-list {
  .activity-item {
    display: flex;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .activity-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 18px;
      flex-shrink: 0;
    }
    
    .activity-content {
      flex: 1;
      
      .activity-title {
        font-size: 15px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 5px;
      }
      
      .activity-description {
        font-size: 13px;
        color: #606266;
        margin-bottom: 5px;
      }
      
      .activity-time {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.edit-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.user-form ::v-deep .el-form-item {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .user-header {
    flex-direction: column;
    text-align: center;
  }
  
  .user-avatar {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .detail-item {
    flex-direction: column;
  }
  
  .detail-item label {
    width: auto;
    margin-bottom: 5px;
  }
}
</style>